
# import sys
import time
import op_route
import logging
import keti4_config as config


class Collector:
    def __init__(self, recv_port=8800, recv_num=4):
        self.recv_port = recv_port
        self.recv_num  = recv_num
        self.result = []
        pass

    # 计算主星接收来自各个计算辅星的计算结果，将结果合并后，输出最终结果
    def run(self):

        print("=== Collector ===")
        print("[Collector] info: recv_port=", self.recv_port)
        print("[Collector] run")


        # 1. 阻塞接收来自各个计算辅星的数据
        results = self.receive_results(recv_port=self.recv_port)

        # 2. 展示各个计算结果
        for i in range(len(results)):
            print(results[i])

        print("________________________")

        self.result = results

        return True

    def res(self) -> list:

        return self.result

    # 启动接收各个计算辅星的计算结果
    def receive_results(self, recv_port = 8800) -> list:

        print("[Collector]<receive_results> 接收计算结果")

        time.sleep(1)

        '''
        result = []
        cnt = self.recv_num
        while(cnt):
            data_type = "TYPE"
            src_id = 0x09 + cnt
            dst_id = 0x01
            data  = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR"
            data_length = len(data) 
            cnt = cnt - 1
            print(f"[Collector]<receive_results> recv one result idx:{cnt}")
            result.append((data_type, src_id, dst_id, data_length, data))

        return result

        '''
        # 接收计算结果
        router = op_route.RouterClient(host='localhost', port=recv_port)
        result = []
        cnt = self.recv_num
        while(cnt):
            data_type, src_id, dst_id, data_length, data = router.receive_packet()
            result.append((data_type, src_id, dst_id, data_length, data))
            cnt = cnt-1

        return result




if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    

    collector = Collector(recv_port=config.recv_port, recv_num=4)
    data = collector.run()